package cl.scene.libbencode;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by IntelliJ IDEA.
 * User: Patricio
 * Date: 23-11-2010
 * Time: 09:36:25 PM
 */
public class ByteStringValue extends NativeType implements Comparable<ByteStringValue> {

    private byte[] value;

    public ByteStringValue(String value) {
        this.value = value.getBytes();
    }

    public ByteStringValue(InputStream is, byte[] firstByte) throws IOException {
        byte[] b= new byte[1];
        int status = BencodeParser.READING_LENGHT;
        String lenStr = new String(firstByte);
        int len = 0;
        int current = 0;
        while(is.read(b) > 0) {
            if(b[0] > 47 && b[0] < 58 && status == BencodeParser.READING_LENGHT) {
                lenStr = lenStr.concat(new String(b));
            } else if (b[0] == ':' && status == BencodeParser.READING_LENGHT) {
                status = BencodeParser.READING_STRING_VALUE;
                len = Integer.parseInt(lenStr);
                value = new byte[len];
            } else if(status == BencodeParser.READING_STRING_VALUE) {
                value[current++] = b[0];
                if(len == current) break;
            }
        }

        System.out.println("String -> " + new String(value));
    }

    public void encodeAndWrite(OutputStream o) throws IOException {
        o.write(Integer.toString(value.length).getBytes());
        o.write(':');
        o.write(value);
    }

    public byte[] getValue() {
        return value;
    }

    public String getValueAsString() {
        return new String(value);
    }

    public void setValue(byte[] value) {
        this.value = value;
    }

    public int compareTo(ByteStringValue o) {
        return o.getValueAsString().compareTo(getValueAsString());
    }
}
